﻿namespace Vin.Tool.Core.GeoCategory;

public class GeoTool
{
    private const double EarthRadiusKm = 6371; // 地球半径，单位为千米

    public static decimal CalculateDistance(decimal lat1, decimal lon1, decimal lat2, decimal lon2)
    {
        // double dLat = (double)ToRadians((lat2 - lat1));
        // double dLon = (double)ToRadians((lon2 - lon2));
        // lat1 = ToRadians(lat1);
        // lat2 = ToRadians(lat2);
        //
        // var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
        //         Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos((double)lat1) * Math.Cos((double)lat2);
        // var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        // var dist = EarthRadiusKm * c;
        //
        // return (decimal)dist;

        // 将经纬度从十进制度数转换为弧度
        double startLatRad = (double)ToRadians(lat1);
        double startLonRad = (double)ToRadians(lon1);
        double endLatRad = (double)ToRadians(lat2);
        double endLonRad = (double)ToRadians(lon2);

        // 经纬度差值
        double dLat = endLatRad - startLatRad;
        double dLon = endLonRad - startLonRad;

        // Haversine公式
        double a = Math.Pow(Math.Sin(dLat / 2), 2) +
                   Math.Cos(startLatRad) * Math.Cos(endLatRad) * Math.Pow(Math.Sin(dLon / 2), 2);
        double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

        // 计算两点间的距离
        double distance = EarthRadiusKm * c;

        return (decimal)distance;
    }

    private static decimal ToRadians(decimal angle)
    {
        return angle * (decimal)(Math.PI / 180);
    }
}